//
// Created by Administrator on 2018/8/9.
//
#include "mingxin.h"
#include "fileutil.h"
#include "MD5.h"
#include "AES.h"
#include "JniUtils.h"
#include <cstdio>
#include <reader.h>
#include "magick_task.h"
#include <iostream>
#include <pthread.h>
#include "License.h"
using namespace rico;

bool MingXin::checkThreadIsRun=false;
bool MingXin::checkWithDeviceIsOK=false;
bool MingXin::checkWithNetIsOK=true;
string MingXin::deviceId="";

MingXin::MingXin(){

}

bool MingXin::check(std::string license){
    if(strcmp(license.c_str(),"")==0){
        return false;
    }
    char* lincenseChar=new char[license.length()];
    strcpy(lincenseChar,license.c_str());
    checkWithDevice(lincenseChar);
    delete(lincenseChar);

    initCheckWithNet(license);
    if(checkWithDeviceIsOK&&checkWithNetIsOK){
        return true;
    }else{
        return false;
    }
}

void MingXin::checkWithDevice(char* license){
    //LOGI("input license :%s",license);
    string deviceLicense=createLicense();
    if(strcmp(license,deviceLicense.c_str())==0){
        checkWithDeviceIsOK= true;
    }else{
        checkWithDeviceIsOK= false;
    }
}

string MingXin::createLicense() {
    License oLicense;
    string mDeviceId=oLicense.createLicense();
    deviceId=mDeviceId;
    //LOGI("device mac :%s",mDeviceId.c_str());
    return mDeviceId;
}


void*  MingXin::checkWithNet(void* args) {

    //GET请求wonder123.imwork.net
    string url = "http://wonder123.imwork.net:28002/face/device?deviceId="+deviceId;//"http://192.168.1.188:28002/face/device";
    WebTask task;
    task.SetUrl(url.c_str());
    task.SetConnectTimeout(5);
    task.DoGetString();
    if (task.WaitTaskDone() != 0) {
        return args;
    }
    //请求服务器成功
    string jsonResult = task.GetResultString();
    Json::Reader reader;
    Json::Value root;
    if (reader.parse(jsonResult, root)) {
        string status = root["status"].asString();
        if(status=="1"){
            string data = root["data"].asString();
            if(data=="false"){
                checkWithNetIsOK=false;
            }else{
                checkWithNetIsOK=true;
            }
        }
    }
    return args;
}

void MingXin::initCheckWithNet(std::string deviceId){

    pthread_t tids[1];

    int ret = pthread_create( &tids[0], NULL, checkWithNet,NULL );

}